package com.lw.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.lw.entity.TbMenu;
import com.lw.entity.TbRoleMenu;
import com.lw.entity.table.TbRoleMenuTableDef;
import com.lw.service.TbRoleMenuService;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.lw.entity.TbRole;
import com.lw.mapper.TbRoleMapper;
import com.lw.service.TbRoleService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static cn.dev33.satoken.SaManager.log;

/**
 * 服务层实现。
 *
 * @author lw
 * @since 2024年08月03日 17:30:24
 */
@Service
public class TbRoleServiceImpl extends ServiceImpl<TbRoleMapper, TbRole> implements TbRoleService {
    @Resource
    TbRoleMenuService tbRoleMenuService;

    @Override
    @Transactional
    public boolean updateMenu(TbRole tbRole) {
        int loginId = StpUtil.getLoginIdAsInt();
        if (tbRole.getId() == null) {
            throw new RuntimeException("参数错误，缺少参数：id");
        }
        //先清空角色菜单表
        QueryWrapper tbRoleMenuQueryWrapper = new QueryWrapper();
        tbRoleMenuQueryWrapper.eq(TbRoleMenuTableDef.TB_ROLE_MENU.ROLE_ID.getName(), tbRole.getId());
        boolean remove = tbRoleMenuService.remove(tbRoleMenuQueryWrapper);
        log.info("删除角色菜单表结果：{}", remove);
        //再插入角色菜单表
        List<TbMenu> menuList = tbRole.getMenuList();
        if (menuList == null || menuList.size() == 0) {
            throw new RuntimeException("参数错误，缺少参数：menuList");
        }
        List<TbRoleMenu> roleMenusList = new ArrayList<>();
        for (TbMenu tbMenu : menuList) {
            TbRoleMenu roleMenu = new TbRoleMenu();
            roleMenu.setRoleId(tbRole.getId());
            roleMenu.setMenuId(tbMenu.getId());
            roleMenu.setCreator(loginId);
            roleMenu.setCreateDate(LocalDateTime.now());
            roleMenusList.add(roleMenu);
        }
        tbRoleMenuService.saveBatch(roleMenusList);
        return true;
    }
}
